import json
from itertools import chain

from django.db.models import F, Q
from django.forms import model_to_dict
from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic import DetailView
from rest_framework import pagination, generics, status, viewsets
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import *
from .serializer import *
import requests

from .utils.jwt_auth import JwtQueryParamsAuthentication, create_token


# Create your views here.


class TestView(APIView):
    def post(self, request):
        file_obj = request.FILES.get('file')
        if not file_obj:
            return Response({'error': '缺少图片文件'})

        # 如果图片需要直接关联到某个ShopModel实体，创建或更新实体
        try:
            # 假设有一个与商店相关的model实例
            shop_instance = UserModel.objects.get(openid='1234567789')
        except UserModel.DoesNotExist:
            shop_instance = UserModel()

        # 保存图片到模型字段，这将自动保存到MEDIA_ROOT指定的位置
        shop_instance.avatar.save(file_obj.name, file_obj, save=True)

        # 或者，如果你不希望直接关联到模型，而是手动保存文件：
        # file_path = default_storage.save(file_obj.name, ContentFile(file_obj.read()))

        # 返回响应
        serializer = UserSerializer(shop_instance)
        return Response(serializer.data)


# 用户通过openid进行登录，将token发送给用户
class LoginAPIView(APIView):
    authentication_classes = []

    def post(self, request):
        code = request.data['data']  # 获取客户端发送过来的code
        # 向微信api接口发送get请求，获取到openid
        url = 'https://api.weixin.qq.com/sns/jscode2session?appid=自己小程序的appid&secret=自己的小程序秘钥&grant_type=authorization_code&js_code=' + code
        res = json.loads(requests.get(url).text)  # 获取回显并解析数据
        print(res)
        openid = res['openid']  # 从解析的数据中拿到openid
        user_object = UserModel.objects.filter(openid=openid).first()  # 过滤
        # 用户不存在的情况
        if not user_object:
            user_object = UserModel.objects.create(openid=openid)
        token = create_token({'id': user_object.id, 'openid': user_object.openid})
        return Response(token)


# 测试解析token
class DrfJwtOrderAVPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        print(request.user)
        return Response('订单列表')


class TestAPI(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        auth = JwtQueryParamsAuthentication()

        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')  # OpenID 存储在 payload 中的 openid 字段

            # 在此处可以根据 OpenID 进行相应操作，例如查询用户信息
            user = UserModel.objects.get(openid=openid)
            seriazer = UserSerializer(user)
            return Response(seriazer.data)

        except Exception as e:
            return Response({'error': str(e)})


# 获取用户的信息
class getUserInfoAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        auth = JwtQueryParamsAuthentication()

        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')  # OpenID 存储在 payload 中的 openid 字段

            # 在此处可以根据 OpenID 进行相应操作，例如查询用户信息
            user = UserModel.objects.get(openid=openid)
            seriazer = UserSerializer(user)
            return Response(seriazer.data)

        except Exception as e:
            return Response({'error': str(e)})


# 上传图片
class UploadAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def post(self, request):
        file_obj = request.FILES.get('file')
        if not file_obj:
            return Response({'error': '缺少图片文件'})
        auth = JwtQueryParamsAuthentication()
        payload, token = auth.authenticate(request)
        openid = payload.get('openid')  # OpenID 存储在 payload 中的 openid 字段
        user_object = UserModel.objects.get(openid=openid)
        user_object.avatar.save(file_obj.name, file_obj, save=True)  # 存储图片
        print(request.data)
        nickname = request.POST.get('nickname')
        introduct = request.POST.get('introduct')
        collage = request.POST.get('collage')
        grade = request.POST.get('grade')
        print(nickname, introduct)
        UserModel.objects.filter(openid=openid).update(avatar=user_object.avatar, nickname=nickname,
                                                       introduct=introduct, collage=collage, grade=grade)
        user = UserModel.objects.get(openid=openid)  # 获取更新后的用户对象
        seriazer = UserSerializer(user)
        return Response(seriazer.data)


# 发布帖子
class publishPostAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def post(self, request):
        auth = JwtQueryParamsAuthentication()

        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')  # OpenID 存储在 payload 中的 openid 字段
            user = UserModel.objects.get(openid=openid)
            content = request.data.get('content')
            post = PostModel.objects.create(author=user, content=content)
            return Response(post.id)


        except Exception as e:
            return Response({'error': str(e)})


# 上传帖子图片
class publishPostImageAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def post(self, request):
        print(request.data)
        print("*" * 200)
        print(request.data.get("postID"))
        print("*" * 200)
        print(request.data.get("circleID"))
        postID = request.data.get('postID')

        post = PostModel.objects.get(id=postID)
        file_obj = request.FILES.get('file')
        if not file_obj:
            return Response({'error': '缺少图片文件'})
        # 创建PostPictureModel对象
        post_picture = PostPictureModel(post=post)  # 如果需要进行关联，需要传入对应的PostModel对象
        # 从请求中获取文件对象，并保存到PostPictureModel对象的picture字段中
        post_picture.picture.save(file_obj.name, file_obj, save=True)
        return Response(post.id)


# 请求帖子数据
class getPostAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        posts = PostModel.objects.all()
        all_posts_data = []

        for post in posts:
            pictures = PostPictureModel.objects.filter(post=post)

            # 将图片URL直接作为字符串存储
            picture_urls = [picture.picture.url for picture in pictures]

            post_data = {
                'id': post.id,
                'author': {
                    'nickname': post.author.nickname,
                    'avatar': post.author.avatar.url,  # 确保这里如果avatar也是ImageFieldFile类型也转为url
                    'openid': post.author.openid
                },
                'content': post.content,
                'pub_time': post.pub_time,
                'likes': post.likes,
                'pictures': picture_urls  # 使用已转换为字符串URL的列表
            }

            all_posts_data.append(post_data)

        # 因为我们已经确保了所有序列化的数据都是JSON可接受的数据类型，现在可以安全地返回
        return JsonResponse(all_posts_data, safe=False)


# 加载帖子
class SmallPostPagination(pagination.PageNumberPagination):
    page_size = 10  # 可以根据需要调整每页的数量


class getPost2APIView(generics.ListAPIView):
    authentication_classes = [JwtQueryParamsAuthentication]
    queryset = PostModel.objects.filter(type=0).order_by('-pub_time')  # 添加排序以避免UnorderedObjectListWarning
    serializer_class = PostSerializer
    pagination_class = SmallPostPagination

    # 可选优化：在序列化器内部计算图片URL，避免每次循环都执行数据库查询
    def get_serializer_context(self):
        context = super().get_serializer_context()
        if 'request' in context:
            # 获取当前请求的post对象集合
            posts = self.get_queryset()
            # 预先获取每个post的所有图片URL
            picture_dict = {}
            for post in posts:
                pictures = PostPictureModel.objects.filter(post=post)
                picture_dict[post.id] = [picture.picture.url for picture in pictures]
            # 将图片URL字典添加到上下文中供序列化器使用
            context['pictures_by_post_id'] = picture_dict
        return context


# 获取帖子详情
class PostDetailAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get_object(self, pk):
        try:
            return PostModel.objects.select_related('author').prefetch_related('commentmodel_set').get(pk=pk)
        except PostModel.DoesNotExist:
            return None

    def get(self, request, pk):
        post = self.get_object(pk)

        if not post:
            return Response(status=status.HTTP_404_NOT_FOUND)

        post_serializer = PostSerializer(post)
        comments = CommentModel.objects.filter(post=post).order_by('-pub_time')
        comments_serializer = CommentSerializer(comments, many=True)

        response_data = {
            'post': post_serializer.data,
            'comments': comments_serializer.data,
        }

        return Response(response_data, status=status.HTTP_200_OK)


# 点赞
class likeStatusAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request, pk):
        auth = JwtQueryParamsAuthentication()
        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')  # OpenID 存储在 payload 中的 openid 字段
            likestatus = LikeModel.objects.filter(post=pk, author__openid=openid).exists()
            print(likestatus)
            return Response(likestatus)
        except Exception as e:
            return Response({'error': str(e)})

    def post(self, request, pk):
        auth = JwtQueryParamsAuthentication()
        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')  # OpenID 存储在 payload 中的 openid 字段
            likestatus = request.data.get('likestatus')
            user = UserModel.objects.get(openid=openid)
            exist_status = LikeModel.objects.filter(post_id=pk, author=user).exists()  # 向数据库检查是否已经点赞
            if likestatus:  # 判断用户是点赞还是取消点赞
                if exist_status:  # 如果用户已经点赞
                    return Response({'status': '已经点赞过啦！'})
                else:  # 此时用户动作是点赞，但是数据库中没有记录
                    LikeModel.objects.create(post_id=pk, author=user)
                    PostModel.objects.filter(id=pk).update(likes=F('likes') + 1)  # 更新post
                    return Response({'status': '成功点赞！'})
            else:  # 判断用户是点赞还是取消点赞，此时是取消点赞
                if exist_status:  # 数据库中有点赞记录，但是用户是取消点赞
                    LikeModel.objects.filter(post_id=pk, author=user).delete()
                    PostModel.objects.filter(id=pk).update(likes=F('likes') - 1)  # 更新post
                    return Response({'status': '成功取消点赞！'})
                else:  # 数据库中没有点赞记录，但是用户是取消点赞
                    return Response({'status': '没有点赞过，取消点赞失败！'})
        except Exception as e:
            return Response({'error': str(e)})


# 添加评论
class addCommentAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def post(self, request, pk):
        auth = JwtQueryParamsAuthentication()
        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')  # OpenID 存储在 payload 中的 openid 字段
            comment = request.data.get('comment')
            user = UserModel.objects.get(openid=openid)
            CommentModel.objects.create(post_id=pk, author=user, content=comment)
            return Response({'status': '成功添加评论！'})
        except Exception as e:
            return Response({'error': str(e)})


# 轮播图
class bannerAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        banner = BannerModel.objects.all()
        banner_serializer = BannerSerializer(banner, many=True)
        return Response(banner_serializer.data)


# 二手商品
class ShopListAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        shops = ShopModel.objects.filter(status=True)
        serializer = ShopModelSerializer(shops, many=True)
        return Response(serializer.data)

    def post(self, request):
        auth = JwtQueryParamsAuthentication()
        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')
            user = UserModel.objects.get(openid=openid)
            name = request.data.get('title')
            content = request.data.get('content')
            price = request.data.get('price')
            picture = request.FILES.get('file')
            shop = ShopModel.objects.create(name=name, content=content, price=price, picture=picture, author=user)
            return Response({'error': "上传成功！", 'shopid': shop.id}, status=status.HTTP_201_CREATED)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)


# 查询单个商品信息
class getShopDetailAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request, pk):
        try:
            shop = ShopModel.objects.get(id=pk)
            serializer = ShopModelSerializer(shop)
            return Response(serializer.data)
        except ShopModel.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)


# 订单
class createOrderAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def post(self, request):
        auth = JwtQueryParamsAuthentication()
        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')
            user = UserModel.objects.get(openid=openid)
            shopid = request.data.get('shopid')
            print(shopid)
            shop = ShopModel.objects.get(id=shopid)
            price = shop.price
            order = OrderModel.objects.create(shop=shop, author=user, price=price)
            ShopModel.objects.filter(id=shopid).update(status=False)
            return Response({'status': '创建订单成功！', 'orderid': order.id}, status=status.HTTP_201_CREATED)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)


class DelShopAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def post(self, request):
        auth = JwtQueryParamsAuthentication()
        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')
            user = UserModel.objects.get(openid=openid)
            shopid = request.data.get('shopid')
            ShopModel.objects.filter(id=shopid).delete()
            return Response("success")
        except ShopModel.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

    def get(self, request):
        auth = JwtQueryParamsAuthentication()
        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')
            user = UserModel.objects.get(openid=openid)
            shop = OrderModel.objects.filter(author=user)
            serializer = OrderSerializer(shop, many=True)
            return Response(serializer.data)
        except OrderModel.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)


class OrderListAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        auth = JwtQueryParamsAuthentication()
        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')
            user = UserModel.objects.get(openid=openid)
            shop = OrderModel.objects.filter(author=user)
            shop2 = OrderModel.objects.filter(shop__author=user, shop__status=False)
            combined_shop = list(chain(shop, shop2))
            serializer = OrderSerializer(combined_shop, many=True)
            return Response(serializer.data)
        except OrderModel.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)


# 获取订单详情
class OrderDetailAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request, pk):
        try:
            # 获取订单详情
            order = OrderModel.objects.select_related('shop').get(id=pk)
            # 获取订单关联的商品
            shop = order.shop
            # 检查用户是否为商品发布者
            is_seller = request.user == shop.author
            # 序列化商品信息，包含图片等详细信息
            shop_serializer = ShopModelSerializer(shop)
            # 将时间格式转换为可直接渲染的时间字符串
            formatted_time = timezone.localtime(order.time).strftime('%Y-%m-%d %H:%M:%S')
            # 构建返回的数据字典，包含userstatus字段和商品信息
            data = {
                'order': {
                    'id': order.id,
                    'shop': shop_serializer.data,
                    'author': order.author.nickname,
                    'price': order.price,
                    'time': formatted_time,
                    'status': order.status,
                },
                'userstatus': is_seller,
            }
            # 返回结果
            return Response(data)
        except OrderModel.DoesNotExist:
            return Response({'error': '订单不存在'}, status=status.HTTP_404_NOT_FOUND)


# 点击完成订单
class OrderFinishAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def post(self, request, pk):
        try:
            order = OrderModel.objects.get(id=pk)
            order.status = True
            order.save()
            return Response({'status': '订单已完成！'})
        except OrderModel.DoesNotExist:
            return Response({'error': '订单不存在'}, status=status.HTTP_404_NOT_FOUND)


# 个人主页，可在这个界面下完成帖子的删除
class myHomeAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        auth = JwtQueryParamsAuthentication()
        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')
            user = UserModel.objects.get(openid=openid)
            posts = PostModel.objects.filter(author=user, type=0)
            serializer = PostSerializer(posts, many=True)
            return Response(serializer.data)
        except PostModel.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)


# 删除帖子
class deletePostAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request, pk):
        try:
            post = PostModel.objects.get(id=pk)
            post.delete()
            return Response({'status': '删除成功！'})
        except PostModel.DoesNotExist:
            return Response({'error': '帖子不存在'}, status=status.HTTP_404_NOT_FOUND)


# 访问其他人的主页
class otherHomeAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request, pk):
        try:
            user = UserModel.objects.get(openid=pk)
            posts = PostModel.objects.filter(author=user, type=0)
            serializer = PostSerializer(posts, many=True)
            return Response(serializer.data)
        except UserModel.DoesNotExist:
            return Response({'error': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)


# 获取点赞评论等数据

class UserPostActivityView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request, *args, **kwargs):
        auth = JwtQueryParamsAuthentication()
        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')
            user = UserModel.objects.get(openid=openid)
            user_posts = PostModel.objects.filter(author=user).order_by('-pub_time')  # 获取当前用户的帖子
            posts_data = PostSerializer(user_posts, many=True).data

            for post_data in posts_data:
                post_id = post_data['id']
                comments = CommentModel.objects.filter(post_id=post_id).exclude(author=user).order_by('-pub_time')
                likes = LikeModel.objects.filter(post_id=post_id).exclude(author=user).order_by('-time')

                post_data['comments'] = CommentSerializer(comments, many=True).data
                post_data['likes'] = LikeSerializer(likes, many=True).data

            return Response(posts_data)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)


# 获取周边商家信息
class StandardResultsSetPagination(pagination.PageNumberPagination):
    page_size = 10  # 自定义每页显示的数量
    page_size_query_param = 'page_size'  # 设置页面大小参数
    max_page_size = 100  # 最大页面大小限制


class ShopInfoViewSet(viewsets.ModelViewSet):
    authentication_classes = [JwtQueryParamsAuthentication]
    queryset = ShopInfoModel.objects.all()
    serializer_class = ShopInfoSerializer
    pagination_class = StandardResultsSetPagination


# 搜索
class PostSearchAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        keyword = request.query_params.get('q', '')
        if keyword:
            # 根据关键词搜索帖子
            posts = PostModel.objects.filter(Q(content__icontains=keyword),type=0)
            serializer = PostSerializer(posts, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            # 如果没有提供关键词，则返回提示信息
            return Response({"message": "请输入搜索关键词"}, status=status.HTTP_400_BAD_REQUEST)


# 关注页
class AttentionsAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        id = request.query_params.get('id')
        try:

            user = UserModel.objects.get(openid=id)
            attentions = FollowModel.objects.filter(author=user)
            serializer = FollowSerializer(attentions, many=True)
        except:
            return Response({'error': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)
        return Response(serializer.data)


# 粉丝页
class FansAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        id = request.query_params.get('id')
        try:
            user = UserModel.objects.get(openid=id)
            attentions = FollowModel.objects.filter(follower=user)
            serializer = FollowSerializer(attentions, many=True)
        except:
            return Response({'error': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)
        return Response(serializer.data)


# 关注
class FollowAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    # 关注
    def post(self, request):
        auth = JwtQueryParamsAuthentication()
        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')
            print("openid is ", openid)
            user = UserModel.objects.get(openid=openid)
            print(request.data.get('follower'))
            follower = UserModel.objects.get(openid=request.data.get('follower'))
            print("用户：", user)
            print("要关注的人", follower)
            print("*" * 100)
            if user == follower:
                return Response({"msg": "不能关注自己", "code": 400})
            if FollowModel.objects.filter(author=user, follower=follower).exists():
                return Response({"msg": "已关注", "code": 400})
            follow = FollowModel.objects.create(author=user, follower=follower)
            follow.save()
            user.attentions += 1
            follower.fans += 1
            user.save()
            follower.save()
            return Response({"msg": "success", "code": 200})
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

    # 取消关注
    def delete(self, request):
        auth = JwtQueryParamsAuthentication()
        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')
            user = UserModel.objects.get(openid=openid)
            follower = UserModel.objects.get(openid=request.data['follower'])
            if user == follower:
                return Response({"msg": "不能取消关注自己", "code": 400})
            if FollowModel.objects.filter(author=user, follower=follower).exists():
                follow = FollowModel.objects.get(author=user, follower=follower)
                follow.delete()
                user.attentions -= 1
                follower.fans -= 1
                user.save()
                follower.save()
                return Response({"msg": "success", "code": 200})
            return Response({"msg": "未关注", "code": 400})
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)


# 用户主页查询关注信息
class getAttentionAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        id = request.query_params.get('id')
        try:
            user = UserModel.objects.get(openid=id)
            print(user)
            attentions = FollowModel.objects.filter(follower=user)
            serializer = FollowSerializer(attentions, many=True)
        except:
            return Response({'error': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)
        return Response(serializer.data)


# 创建圈子
class CircleCreateAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def post(self, request):
        auth = JwtQueryParamsAuthentication()
        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')
            user = UserModel.objects.get(openid=openid)
            image = request.FILES.get('file')
            if not image:
                return Response({'error': '缺少图片文件'})
            circle_status = CircleModel.objects.filter(name=request.data['name'])
            if circle_status:
                return Response({"msg": "圈子已存在"}, status=status.HTTP_402_PAYMENT_REQUIRED)
            number = CircleModel.objects.filter(author=user).count()
            if number >= 3:
                return Response({"msg": "每个用户最多只能创建三个圈子"}, status=status.HTTP_403_FORBIDDEN)
            circle = CircleModel.objects.create(name=request.data['name'], content=request.data['content'],
                                                picture=image, author=user, )
            circle.save()
            return Response({"msg": "success", "code": 200})
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)


# 获取圈子列表
class CircleListAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        circles = CircleModel.objects.all()
        # 按照圈子人数降序
        circles = sorted(circles, key=lambda x: x.number, reverse=True)
        serializer = CircleSerializer(circles, many=True)
        return Response(serializer.data)


# 获取单个圈子信息
class CircleDetailAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        id = request.query_params.get('id')
        try:
            circle = CircleModel.objects.get(id=id)
            serializer = CircleSerializer(circle)
        except:
            return Response({'error': '圈子不存在'}, status=status.HTTP_404_NOT_FOUND)
        return Response(serializer.data)


# 获取该成员是否在圈子里面
class CircleMemberAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        auth = JwtQueryParamsAuthentication()
        payload, token = auth.authenticate(request)
        openid = payload.get('openid')
        user = UserModel.objects.get(openid=openid)
        id = request.query_params.get('id')
        try:
            circle = CircleModel.objects.get(id=id)
            members = CircleMemberModel.objects.filter(circle=circle)
            serializer = CircleMemberSerializer(members, many=True)
        except:
            return Response({'error': '圈子不存在'}, status=status.HTTP_404_NOT_FOUND)
        if circle.author == user:
            return Response({"status": True}, status=status.HTTP_200_OK)
        if CircleMemberModel.objects.filter(circle=circle, member=user).exists():
            return Response({"status": True}, status=status.HTTP_200_OK)
        else:
            return Response({"status": False}, status=status.HTTP_404_NOT_FOUND)


# 申请加入圈子
class CircleMemberCreateAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    # def get(self, request):
    #     auth = JwtQueryParamsAuthentication()
    #     try:
    #         payload, token = auth.authenticate(request)
    #         openid = payload.get('openid')
    #         user = UserModel.objects.get(openid=openid)
    #         circle = CircleModel.objects.get(id=request.query_params.get('id'))
    #         if CircleMemberModel.objects.filter(circle=circle, member=user).exists():
    #             return Response({"msg": "已加入圈子", "code": 400})
    #         CircleMemberModel.objects.create(circle=circle, member=user)
    #         circle.number += 1
    #         circle.save()
    #         return Response({"msg": "success", "code": 200})
    #     except Exception as e:
    #         return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
    def get(self, request):
        auth = JwtQueryParamsAuthentication()
        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')
            user = UserModel.objects.get(openid=openid)
            circle = CircleModel.objects.get(id=request.query_params.get('id'))
            if CircleMemberModel.objects.filter(circle=circle, member=user).exists():
                return Response({"msg": "已加入圈子", "code": 400})
            if CircleApplyModel.objects.filter(circle=circle, author=user).exists():
                return Response({"msg": "已申请加入圈子", "code": 400})
            CircleApplyModel.objects.create(circle=circle, author=user)
            return Response({"msg": "success", "code": 200})
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)


# 退出圈子
class CircleMemberDeleteAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        auth = JwtQueryParamsAuthentication()
        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')
            user = UserModel.objects.get(openid=openid)
            circle = CircleModel.objects.get(id=request.query_params.get('id'))
            if circle.author == user:
                return Response({"msg": "不能退出圈子", "code": 400})
            if CircleMemberModel.objects.filter(circle=circle, member=user).exists():
                CircleMemberModel.objects.filter(circle=circle, member=user).delete()
                circle.number -= 1
                circle.save()
                return Response({"msg": "success", "code": 200})
            else:
                return Response({"msg": "未加入圈子", "code": 400})
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)


# 发布帖子
class circlePublishPostAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def post(self, request):
        auth = JwtQueryParamsAuthentication()

        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')  # OpenID 存储在 payload 中的 openid 字段
            user = UserModel.objects.get(openid=openid)
            content = request.data.get('content')
            post = PostModel.objects.create(author=user, content=content, type=request.data.get('circleID'))
            return Response(post.id)
        except Exception as e:
            return Response({'error': str(e)})


# 加载帖子
class CircleSmallPostPagination(pagination.PageNumberPagination):
    page_size = 10  # 可以根据需要调整每页的数量


class CircleGetPostAPIView(generics.ListAPIView):
    authentication_classes = [JwtQueryParamsAuthentication]
    serializer_class = PostSerializer
    pagination_class = CircleSmallPostPagination

    def get_queryset(self):
        circle_id = self.request.query_params.get('circleid')  # 从请求数据中获取圈子ID
        if circle_id:
            return PostModel.objects.filter(type=circle_id).order_by('-pub_time')
        else:
            return PostModel.objects.none()  # 返回空查询集以避免未指定圈子ID时返回所有数据

    # 可选优化：在序列化器内部计算图片URL，避免每次循环都执行数据库查询
    def get_serializer_context(self):
        context = super().get_serializer_context()
        if 'request' in context:
            # 获取当前请求的post对象集合
            posts = self.get_queryset()
            # 预先获取每个post的所有图片URL
            picture_dict = {}
            for post in posts:
                pictures = PostPictureModel.objects.filter(post=post)
                picture_dict[post.id] = [picture.picture.url for picture in pictures]
            # 将图片URL字典添加到上下文中供序列化器使用
            context['pictures_by_post_id'] = picture_dict
        return context


# 圈子里面删除帖子
class CircleDeletePostAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        auth = JwtQueryParamsAuthentication()
        try:
            payload, token = auth.authenticate(request)
            openid = payload.get('openid')
            user = UserModel.objects.get(openid=openid)
            post = PostModel.objects.get(id=request.query_params.get('id'))
            master = CircleModel.objects.get(author__openid=request.query_params.get('master')).author
            if post.author == user or master == user:
                post.delete()
                return Response({"msg": "success", "code": 200})
            else:
                return Response({"msg": "不能删除别人的帖子"}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)


# 获取我创建的圈子列表
class MyCircleListAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        auth = JwtQueryParamsAuthentication()
        payload, token = auth.authenticate(request)
        openid = payload.get('openid')
        user = UserModel.objects.get(openid=openid)
        circles = CircleModel.objects.filter(author=user)
        # 按照圈子人数降序
        circles = sorted(circles, key=lambda x: x.number, reverse=True)
        serializer = CircleSerializer(circles, many=True)
        return Response(serializer.data)


# 获取申请加入圈子的列表
class CircleApplyListAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        auth = JwtQueryParamsAuthentication()
        payload, token = auth.authenticate(request)
        openid = payload.get('openid')
        user = UserModel.objects.get(openid=openid)
        id = request.query_params.get('id')
        circle = CircleModel.objects.get(id=id)
        if circle.author == user:
            apply_user = CircleApplyModel.objects.filter(circle=circle, status=False)
            serializer = CircleApplySerializer(apply_user, many=True)
            if not serializer.data:
                return Response({"msg": "没有申请", "code": 400})
            else:
                return Response({"msg": "success", "code": 200, "data": serializer.data})
        else:
            return Response({"msg": "没有权限", "code": 400})


# 通过申请同意用户加入圈子
class CircleApplyAPIView(APIView):
    authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request):
        auth = JwtQueryParamsAuthentication()
        payload, token = auth.authenticate(request)
        openid = payload.get('openid')
        user = UserModel.objects.get(openid=openid)
        id = request.query_params.get('id')
        userid = request.query_params.get('userid')
        circle = CircleModel.objects.get(id=id)
        print(circle)
        if circle.author == user:
            apply_user = CircleApplyModel.objects.get(circle=circle, author__openid=userid, status=False)
            # 如果已经在圈子里面了
            if CircleMemberModel.objects.filter(circle=circle, member__openid=userid).exists():
                return Response({"msg": "已经在圈子里面了", "code": 400})
            apply_user.status = True
            apply_user.save()
            CircleMemberModel.objects.create(circle=circle, member=apply_user.author)
            circle.number += 1
            circle.save()
            return Response({"msg": "success", "code": 200})
        else:
            return Response({"msg": "没有权限", "code": 400})
